package infra

import (
	"context"
	"database/sql"
	"fmt"
	"os"
	"runtime"
	"time"

	"gitee.com/h2ob/base"
	"github.com/boltdb/bolt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/mysqldialect"
)

type H2oDB struct {
	db  *bun.DB
	kv  *bolt.DB
	ctx *context.Context
}

var gH2oDb *H2oDB = &H2oDB{}

func (hDb *H2oDB) open(ctx *context.Context) {
	sqldb, err := sql.Open("mysql", base.GConf.Infra.MyDns)
	if err != nil {
		base.GLogger.Warnf("Connect to [%s] failed:%s", base.GConf.Infra.MyDns, err)
		panic(err)
	}
	maxOpenConns := 4 * runtime.GOMAXPROCS(0)
	sqldb.SetMaxOpenConns(maxOpenConns)
	sqldb.SetMaxIdleConns(2)
	sqldb.SetConnMaxIdleTime(1 * time.Minute)
	sqldb.SetConnMaxLifetime(5 * time.Minute)
	db := bun.NewDB(sqldb, mysqldialect.New())
	hDb.db = db
	hDb.ctx = ctx

	os.MkdirAll(fmt.Sprintf("%s/blot", base.GConf.Infra.KvDns), 0755)
	dbName := fmt.Sprintf("%s/blot/blot.db", base.GConf.Infra.KvDns)
	kv, err := bolt.Open(dbName, 0600, nil)
	if err != nil {
		base.GLogger.Infof("Open db:%s, failed:%s", dbName, err)
		panic(err)
	}
	hDb.kv = kv
}

func (hDb *H2oDB) close() {
	if hDb.db != nil {
		hDb.db.Close()
	}
	if hDb.kv != nil {
		hDb.kv.Close()
	}
}
